package com.donglan.pethome.user.controller;

import com.donglan.pethome.basic.util.AjaxResult;
import com.donglan.pethome.user.constant.WechatConstant;
import com.donglan.pethome.user.domain.vo.UserVo;
import com.donglan.pethome.user.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author: zhangdonghui
 * @Date: 2022/1/21 2:45
 *
 * 微信相关的controller
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatService wechatService;


    /*
     * 功能描述 申请授权码(其实就是拉取二维码，扫描二维码完成登录)
     * @author zhangdonghui
     * @date 2022/1/21 2:51
     * @param
     * @return java.lang.String
     */
    @GetMapping("/toRequestCode")
    public String toRequestCode(){
        // 获取授权二维码的url地址
        String codeUrl = WechatConstant.CODEURL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        // 跨域进行访问
        return "redirect:"+codeUrl;
    }

    /*
     * 功能描述 扫码成功之后的回调接口
     * @author zhangdonghui
     * @date 2022/1/21 11:35
     * @param code
     * @return java.lang.String
     */
    @RequestMapping("/callback")
    public String callback(String code) {
        System.out.println("授权码："+code);
        //跳转到门户网站callback.html页面，在此页面发送ajax请求获取token
        return "redirect:http://localhost:8082/callback.html?code=" + code;
    }

    /*
     * 功能描述 处理回调请求，通过授权码获取token
     * @author zhangdonghui
     * @date 2022/1/21 12:34
     * @param param
     * @return AjaxResult
     */
    @PostMapping("/handleCallBack")
    @ResponseBody
    public AjaxResult handleCallBack(@RequestBody Map<String,String> param){

        try {
            // 获取授权码
            String code = param.get("code");
            // 通过授权码获取token
            Map<String, Object> map = wechatService.handleCallBack(code);
            // 将返回的数据封装到Map对象中，响应到前端
            // 跳转到绑定页面或者直接登录
            return new AjaxResult().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }

    }

    /*
     * 功能描述 绑定微信用户信息
     * @author zhangdonghui
     * @date 2022/1/21 23:22
     * @param userVo
     * @return com.donglan.pethome.basic.util.AjaxResult
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody UserVo userVo){
        try {
            //微信和用户绑定在一起
            Map<String, Object> map = wechatService.binder(userVo);
            return new AjaxResult().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }

    }





}
